<?php

namespace app\core;

use app\model\SysDept;
use app\model\SysRoleDept;
use app\model\SysUser;
use app\service\UserService;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * 公共模型
 */
class BaseModel extends Model
{
    /**
     * 自动写入create_time/update_time
     * @var string|boolean
     */
    protected $autoWriteTimestamp = 'datetime';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';

    /**
     * 自动写 create_by/update_by
     * @var bool
     */
    protected $autoWriteBy = true;

    public static function onBeforeInsert($model)
    {
        $autoWriteBy = $model->autoWriteBy ?? false;
        $by = Request::invoke()->getUser("user_name");
        if ($autoWriteBy && !empty($by)) {
            $model->create_by = $by;
        }
    }

    public static function onBeforeUpdate($model)
    {
        $autoWriteBy = $model->autoWriteBy ?? false;
        $by = Request::invoke()->getUser("user_name");
        if ($autoWriteBy && !empty($by)) {
            $model->update_by = $by;
        }
    }

    /**
     * 角色数据权限 ->scope(['data'])
     * @param $query
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function scopeData($query)
    {
        $request = Request::invoke();
        $user = $request->getUser();
        if (!empty($user) && !$request->isSuperAdmin()) {
            $roles = UserService::invoke()->getRoles($user['user_id'])['roles'] ?? [];
            if (count($roles) > 0) {
                $query->where(function ($q) use ($roles, $user) {
                    $conditions = [];
                    foreach ($roles as $role) {
                        if ($role['data_scope'] != Constant::DATA_SCOPE_DIV && in_array($role['data_scope'], $conditions)) {
                            continue;
                        }
                        if ($role['data_scope'] == Constant::DATA_SCOPE_ALL) {
                            // 全部数据权限
                            break;
                        }
                        if ($role['data_scope'] == Constant::DATA_SCOPE_DIV) {
                            // 自定数据权限
                            $sql = SysRoleDept::where('role_id', $role['role_id'])
                                ->field('dept_id')
                                ->buildSql();
                            $q = $q->whereOr('dept_id', "exp", "in $sql");
                        }
                        if ($role['data_scope'] == Constant::DATA_SCOPE_DEPT) {
                            // 本部门数据权限
                            $q = $q->whereOr("dept_id", $user['dept_id']);
                        }
                        if ($role['data_scope'] == Constant::DATA_SCOPE_DEPTS) {
                            // 本部门及以下数据权限
                            $sql = SysDept::where(function ($q1) use ($user) {
                                $q1->whereOr('dept_id', $user['dept_id'])
                                    ->whereOr(function ($q2) use ($user) {
                                        $q2->whereFindInSet('ancestors', $user['dept_id']);
                                    });
                            })->field('dept_id')->buildSql();
                            $q = $q->whereOr("dept_id", "exp", "in $sql");
                        }
                        if ($role['data_scope'] == Constant::DATA_SCOPE_SELF) {
                            // 仅本人数据权限
                            $sql = SysUser::where('user_id', $user['user_id'])->field('user_name')->buildSql();
                            $q = $q->whereOr('create_by', 'exp', "= $sql");
                        }
                        $conditions[] = $role['data_scope'];
                    }
                });
            }
        }
    }

}